<template>
  <d-modal :title="(type === '0' ? '新增' : '修改') + '菜单'" :visible="visible" :width="400" @ok="handleSubmit"
    @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="菜单名称" name="menuName">
        <a-input v-model:value="formState.menuName" placeholder="请输入菜单名称！" />
      </a-form-item>
      <a-form-item label="路由名称" name="menuRouteName">
        <a-input v-model:value="formState.menuRouteName" placeholder="请输入路由名称！" />
      </a-form-item>
      <a-form-item label="菜单地址" name="menuUrl">
        <a-input v-model:value="formState.menuUrl" placeholder="请输入菜单地址！" />
      </a-form-item>
      <a-form-item label="菜单图标" name="menuIcon">
        <a-input v-model:value="formState.menuIcon" placeholder="请输入菜单地址！" />
      </a-form-item>
      <a-form-item label="排序" name="menuSort">
        <a-input-number v-model:value="formState.menuSort" placeholder="请输入排序！" min="0" style="width: 100%" />
      </a-form-item>
    </a-form>
  </d-modal>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { save, update } from '@/api/menu/index'

const emits = defineEmits(['ok'])
const visible = ref(false)
const type = ref('0')
const formRef = ref()
const formState = ref({ menuSort: 0 })
const rules = ref({
  menuName: [{ required: true, message: '请输入菜单名称！' }],
  menuRouteName: [{ required: true, message: '请输入路由名称！' }],
  menuUrl: [{ required: true, message: '请输入菜单地址！' }],
  menuIcon: [{ required: true, message: '请选择菜单图标！' }],
  menuSort: [{ required: true, message: '请输入排序！' }]
})

const add = (t, parentId) => {
  type.value = t
  formState.value = { menuSort: 0, parentId }
  visible.value = true
}

const edit = (t, record) => {
  type.value = t
  formState.value = record
  visible.value = true
}

const handleCancel = () => {
  formState.value = {}
  visible.value = false
}

const handleSubmit = () => {
  formRef.value.validate().then(() => {
    (type.value === '0' ? save(formState.value) : update(formState.value)).then((res) => {
      if (res.code === 0) {
        emits('ok')
        handleCancel()
      } else {
        message.error(res.message)
      }
    })
  })
}

defineExpose({
  add,
  edit
})
</script>